package com.util;

import com.baseEnum.BaseEnum;
import com.baseEnum.SystemEnum;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EnumTypeHandler implements TypeHandler<BaseEnum> {
    private final static Logger logger = LoggerFactory.getLogger(EnumTypeHandler.class);

    public void setParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException {
        logger.debug("name : " + parameter.getName() + ", value : " + parameter.getValue());
        ps.setObject(i, parameter.getValue());
    }

    public BaseEnum getResult(ResultSet rs, String columnName) throws SQLException {
        Integer value = (Integer) rs.getInt(columnName);
        SystemEnum systemEnum = SystemEnum.get(columnName);
        if (systemEnum == null) {
            return null;
        }
        if (value == null) {
            return systemEnum.getDefault();
        } else {
            return systemEnum.getEnum(value);
        }
    }

    public BaseEnum getResult(ResultSet rs, int i) throws SQLException {
        return null;
    }

    public BaseEnum getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }

}
